package com.dbappsecurity.network;

import com.dbappsecurity.network.client.NetworkClient;
import com.dbappsecurity.network.download.Download;
import com.google.gson.Gson;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import okhttp3.HttpUrl;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by Arirus on 2018/4/2.
 */

public class Thunder {
  private static Map<String, Thunder> map = new ConcurrentHashMap<>();

  Retrofit mRetrofit;
  Gson mGson;
  HttpUrl mHost;

  public Api newApi() {
    return new Api(this, mGson);
  }

  public Download newDownload(String url){
    return new Download(url,mRetrofit);
  }

  private Thunder(HttpUrl host, NetworkClient client, Gson gson) {
    mGson = gson;
    mHost = host;
    mRetrofit = new Retrofit.Builder().client(client.getClient())
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .addConverterFactory(ScalarsConverterFactory.create())
        .addConverterFactory(GsonConverterFactory.create(gson))
        .baseUrl(host)
        .build();
  }

  public Retrofit getRetrofit() {
    return mRetrofit;
  }

  public Gson getGson() {
    return mGson;
  }

  public HttpUrl getHost() {
    return mHost;
  }

  public static class Builder {
    NetworkClient mClient;
    Gson mGson;
    HttpUrl mHost;

    public Thunder build() {
      if (mHost == null) throw new IllegalStateException("Base URL required.");
      if (mGson == null) mGson = new Gson();
      if (mClient == null) mClient = NetworkClient.newInstance(NetworkClient.Logger.NONE);
      return new Thunder(mHost, mClient, mGson);
    }

    public Builder baseUrl(String baseUrl) {
      HttpUrl httpUrl = HttpUrl.parse(baseUrl);
      if (httpUrl == null) {
        throw new IllegalArgumentException("Illegal URL: " + baseUrl);
      }
      mHost = httpUrl;
      return this;
    }

    public Builder gsonConverter(Gson gson) {
      mGson = gson;
      return this;
    }

    public Builder networkClient(NetworkClient networkClient) {
      mClient = networkClient;
      return this;
    }

    public Builder networkClient(NetworkClient.Logger level) {
      mClient = NetworkClient.newInstance(level);
      return this;
    }
  }
}
